import { Module } from 'vuex'
import router from '@/router'

import { IRootState } from '../../types' // 类型
import { ILoginState } from './types'

import {
  accountLoginRequest,
  requestUserInfoById,
  requestUserMenusByRoleId
} from '@/service/login/login' // 接口

import { mapMenusToRoutes } from '@/utils/map-menus'

import localChe from '@/utils/cache'

const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenus: []
    }
  },
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    changeUserMenus(state, userMenus: any) {
      state.userMenus = userMenus

      // userMenus => 映射到 router
      const routeArr = mapMenusToRoutes(userMenus)
      // console.log(routeArr)

      routeArr.forEach((item) => {
        router.addRoute('main', item)
      })
    }
  },
  actions: {
    async accountLoginActions({ commit }, payload: any) {
      // 拿到token
      const result = await accountLoginRequest(payload)
      // console.log(result)
      const { id, token } = result.data
      commit('changeToken', token)
      // 把token 存放在localStorage中
      localChe.setCache('token', token)

      // 请求用户信息
      const userInfoResult = await requestUserInfoById(id)
      const userInfo = userInfoResult.data
      commit('changeUserInfo', userInfo)
      localChe.setCache('userInfo', userInfo)

      // 请求用户菜单
      const UserMenusResult = await requestUserMenusByRoleId(userInfo.role.id)
      const UserMenus = UserMenusResult.data
      commit('changeUserMenus', UserMenus)
      localChe.setCache('UserMenus', UserMenus)
      // console.log(UserMenus)
      //跳转到首页
      router.push('/')
    },

    loadLocalLogin({ commit }) {
      const token = localChe.getCache('token')
      if (token) {
        commit('changeToken', token)
      }
      const userInfo = localChe.getCache('userInfo')
      if (userInfo) {
        commit('changeUserInfo', userInfo)
      }
      const UserMenus = localChe.getCache('UserMenus')
      if (UserMenus) {
        commit('changeUserMenus', UserMenus)
      }
    }
  }
}

export default loginModule
